<template>
  <div class="table-columns-panel-v2">
    <!-- 头部工具栏 -->
    <div class="panel-header bg-white px-6 py-4 border-b border-gray-200 sticky top-0 z-10">
      <div class="flex items-center justify-between">
        <div>
          <h3 class="text-lg font-semibold text-gray-800">列设计</h3>
          <p class="text-sm text-gray-500 mt-1">定义表的列结构，支持拖拽调整顺序</p>
        </div>
        <div class="flex items-center space-x-2">
          <el-input
            v-model="searchQuery"
            placeholder="搜索列名..."
            prefix-icon="Search"
            size="small"
            clearable
            class="w-48"
          />
          <el-button type="primary" @click="addColumn">
            <el-icon><Plus /></el-icon>
            添加列
          </el-button>
          <el-button @click="batchOperations">
            <el-icon><Setting /></el-icon>
            批量操作
          </el-button>
        </div>
      </div>
    </div>

    <!-- 主体内容 -->
    <div class="table-container p-6">
      <!-- 使用Element Plus增强表格 -->
      <el-table
        ref="columnTable"
        :data="filteredColumns"
        row-key="_id"
        border
        stripe
        highlight-current-row
        @selection-change="handleSelectionChange"
        @cell-dblclick="handleCellDblClick"
        class="modern-table"
        :max-height="tableMaxHeight"
        :scrollbar-always-on="true"
        :default-sort="{ prop: 'position', order: 'ascending' }"
      >
        <!-- 选择列 -->
        <el-table-column
          type="selection"
          width="50"
          fixed="left"
          align="center"
        />

        <!-- 拖拽排序列 -->
        <el-table-column
          width="50"
          fixed="left"
          align="center"
        >
          <template #default>
            <el-icon class="drag-handle cursor-move text-gray-400 hover:text-gray-600">
              <Grid />
            </el-icon>
          </template>
        </el-table-column>

        <!-- 列名 -->
        <el-table-column
          prop="name"
          label="列名"
          width="180"
          fixed="left"
          sortable
        >
          <template #default="{ row, $index }">
            <el-input
              v-model="row.name"
              size="small"
              @change="() => handleColumnChange($index)"
              class="column-input"
            >
              <template #suffix>
                <el-icon v-if="row.primaryKey" class="text-warning">
                  <Key />
                </el-icon>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 数据类型 -->
        <el-table-column
          prop="type"
          label="数据类型"
          width="180"
          sortable
        >
          <template #default="{ row, $index }">
            <el-select
              v-model="row.type"
              size="small"
              @change="(val) => handleTypeChange(val, $index)"
              class="w-full"
              filterable
            >
              <template #prefix>
                <el-icon :class="getTypeIconClass(row.type)">
                  <component :is="getTypeIcon(row.type)" />
                </el-icon>
              </template>
              <el-option-group
                v-for="(group, name) in dataTypeGroups"
                :key="name"
                :label="name"
              >
                <el-option
                  v-for="type in group"
                  :key="type.value"
                  :label="type.label"
                  :value="type.value"
                >
                  <div class="flex items-center justify-between">
                    <span>{{ type.label }}</span>
                    <span class="text-xs text-gray-400">{{ type.description }}</span>
                  </div>
                </el-option>
              </el-option-group>
            </el-select>
          </template>
        </el-table-column>

        <!-- 长度/精度 -->
        <el-table-column
          prop="length"
          label="长度/精度"
          width="120"
          sortable
        >
          <template #default="{ row, $index }">
            <el-input
              v-if="needsLength(row.type)"
              v-model="row.length"
              :placeholder="getLengthPlaceholder(row.type)"
              size="small"
              @change="() => handleColumnChange($index)"
            >
              <template #append v-if="needsPrecision(row.type)">
                <el-input
                  v-model="row.scale"
                  placeholder="小数"
                  style="width: 60px"
                  @change="() => handleColumnChange($index)"
                />
              </template>
            </el-input>
            <el-select
              v-else-if="row.type === 'enum' || row.type === 'set'"
              v-model="row.values"
              multiple
              filterable
              allow-create
              default-first-option
              placeholder="输入值"
              size="small"
              class="w-full"
              @change="() => handleColumnChange($index)"
            >
              <el-option
                v-for="item in row.values"
                :key="item"
                :label="item"
                :value="item"
              />
            </el-select>
            <span v-else class="text-gray-400 text-sm">-</span>
          </template>
        </el-table-column>

        <!-- 默认值 -->
        <el-table-column
          prop="defaultValue"
          label="默认值"
          width="180"
          sortable
        >
          <template #default="{ row, $index }">
            <el-input
              v-model="row.defaultValue"
              placeholder="默认值"
              size="small"
              @change="() => handleColumnChange($index)"
            >
              <template #append>
                <el-dropdown @command="(cmd) => setDefaultValue($index, cmd)" trigger="click">
                  <el-button size="small" class="px-2">
                    <el-icon><More /></el-icon>
                  </el-button>
                  <template #dropdown>
                    <el-dropdown-menu>
                      <el-dropdown-item command="NULL">NULL</el-dropdown-item>
                      <el-dropdown-item command="CURRENT_TIMESTAMP">当前时间</el-dropdown-item>
                      <el-dropdown-item command="">空字符串</el-dropdown-item>
                      <el-dropdown-item command="0">0</el-dropdown-item>
                      <el-dropdown-item v-if="props.databaseType === 'dameng'" command="SYSDATE">达梦SYSDATE</el-dropdown-item>
                      <el-dropdown-item v-if="props.databaseType === 'dameng'" command="SYSTIMESTAMP">达梦SYSTIMESTAMP</el-dropdown-item>
                    </el-dropdown-menu>
                  </template>
                </el-dropdown>
              </template>
            </el-input>
          </template>
        </el-table-column>

        <!-- 约束 -->
        <el-table-column
          label="约束"
          width="280"
        >
          <template #default="{ row, $index }">
            <div class="constraints-checkboxes">
              <el-checkbox
                v-model="row.notNull"
                @change="() => handleNotNullChange($index)"
                size="small"
              >
                非空
              </el-checkbox>
              <el-checkbox
                v-model="row.primaryKey"
                @change="() => handlePrimaryKeyChange($index)"
                size="small"
              >
                主键
              </el-checkbox>
              <el-checkbox
                v-model="row.autoIncrement"
                :disabled="!canAutoIncrement(row)"
                @change="() => handleAutoIncrementChange($index)"
                size="small"
              >
                自增
              </el-checkbox>
              <el-checkbox
                v-model="row.unique"
                @change="() => handleColumnChange($index)"
                size="small"
              >
                唯一
              </el-checkbox>
            </div>
          </template>
        </el-table-column>

        <!-- 注释 -->
        <el-table-column
          prop="comment"
          label="注释"
          min-width="200"
        >
          <template #default="{ row, $index }">
            <el-input
              v-model="row.comment"
              placeholder="列注释"
              size="small"
              @change="() => handleColumnChange($index)"
            />
          </template>
        </el-table-column>

        <!-- 高级选项 -->
        <el-table-column
          label="高级选项"
          width="120"
          fixed="right"
        >
          <template #default="{ $index }">
            <el-button
              type="primary"
              link
              size="small"
              @click="showAdvancedOptions($index)"
            >
              <el-icon><Setting /></el-icon>
              高级
            </el-button>
          </template>
        </el-table-column>

        <!-- 操作列 -->
        <el-table-column
          label="操作"
          width="100"
          fixed="right"
          align="center"
        >
          <template #default="{ $index }">
            <el-button
              type="danger"
              link
              size="small"
              @click="removeColumn($index)"
            >
              <el-icon><Delete /></el-icon>
              删除
            </el-button>
          </template>
        </el-table-column>
      </el-table>

      <!-- 空状态 -->
      <div v-if="localColumns.length === 0" class="empty-state text-center py-12">
        <el-empty description="还没有添加任何列">
          <el-button type="primary" @click="addColumn">
            <el-icon><Plus /></el-icon>
            添加第一列
          </el-button>
        </el-empty>
      </div>
    </div>

    <!-- 高级选项对话框 -->
    <el-dialog
      v-model="showAdvancedDialog"
      :title="`高级选项 - ${currentColumn?.name || ''}`"
      width="600px"
    >
      <el-form v-if="currentColumn" label-width="120px">
        <el-form-item label="字符集" v-if="isStringType(currentColumn.type)">
          <el-select
            v-model="currentColumn.charset"
            placeholder="继承表设置"
            clearable
          >
            <el-option label="utf8mb4" value="utf8mb4" />
            <el-option label="utf8" value="utf8" />
            <el-option label="latin1" value="latin1" />
            <el-option label="gbk" value="gbk" />
            <el-option v-if="props.databaseType === 'dameng'" label="UTF8" value="UTF8" />
            <el-option v-if="props.databaseType === 'dameng'" label="GBK" value="GBK" />
            <el-option v-if="props.databaseType === 'dameng'" label="GB18030" value="GB18030" />
          </el-select>
        </el-form-item>

        <el-form-item label="排序规则" v-if="isStringType(currentColumn.type)">
          <el-select
            v-model="currentColumn.collation"
            placeholder="继承字符集设置"
            clearable
          >
            <el-option label="utf8mb4_general_ci" value="utf8mb4_general_ci" />
            <el-option label="utf8mb4_unicode_ci" value="utf8mb4_unicode_ci" />
            <el-option label="utf8mb4_bin" value="utf8mb4_bin" />
          </el-select>
        </el-form-item>

        <el-form-item label="字符长度语义" v-if="isStringType(currentColumn.type) && props.databaseType === 'dameng'">
          <el-radio-group v-model="currentColumn.semanticType">
            <el-radio label="BYTE">字节语义</el-radio>
            <el-radio label="CHAR">字符语义</el-radio>
          </el-radio-group>
          <div class="text-xs text-gray-500 mt-1">字节语义下长度以字节为单位，字符语义下长度以字符为单位</div>
        </el-form-item>

        <el-form-item label="存储选项" v-if="props.databaseType === 'mysql'">
          <el-select
            v-model="currentColumn.storage"
            placeholder="默认"
            clearable
          >
            <el-option label="DEFAULT" value="DEFAULT" />
            <el-option label="DISK" value="DISK" />
            <el-option label="MEMORY" value="MEMORY" />
          </el-select>
        </el-form-item>

        <el-form-item label="其他属性">
          <el-input
            v-model="currentColumn.extra"
            placeholder="如: ON UPDATE CURRENT_TIMESTAMP"
          />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showAdvancedDialog = false">取消</el-button>
        <el-button type="primary" @click="saveAdvancedOptions">确定</el-button>
      </template>
    </el-dialog>

    <!-- 批量操作对话框 -->
    <el-dialog
      v-model="showBatchDialog"
      title="批量操作"
      width="500px"
    >
      <el-form label-width="100px">
        <el-form-item label="操作类型">
          <el-radio-group v-model="batchAction">
            <el-radio label="setNotNull">设置非空</el-radio>
            <el-radio label="removeNotNull">移除非空</el-radio>
            <el-radio label="setCharset">设置字符集</el-radio>
            <el-radio label="setComment">设置注释前缀</el-radio>
          </el-radio-group>
        </el-form-item>

        <el-form-item label="字符集" v-if="batchAction === 'setCharset'">
          <el-select v-model="batchCharset" placeholder="选择字符集">
            <el-option label="utf8mb4" value="utf8mb4" />
            <el-option label="utf8" value="utf8" />
            <el-option label="gbk" value="gbk" />
            <el-option v-if="props.databaseType === 'dameng'" label="UTF8" value="UTF8" />
            <el-option v-if="props.databaseType === 'dameng'" label="GBK" value="GBK" />
          </el-select>
        </el-form-item>

        <el-form-item label="注释前缀" v-if="batchAction === 'setComment'">
          <el-input v-model="batchCommentPrefix" placeholder="输入注释前缀" />
        </el-form-item>
      </el-form>
      <template #footer>
        <el-button @click="showBatchDialog = false">取消</el-button>
        <el-button type="primary" @click="executeBatchOperation">执行</el-button>
      </template>
    </el-dialog>
  </div>
</template>

<script setup>
import { ref, computed, watch, onMounted, onBeforeUnmount, nextTick } from 'vue'
import { 
  Plus, 
  Delete, 
  Setting,
  Grid,
  Search,
  More,
  Document,
  Clock,
  Link,
  Key,
  Calendar
} from '@element-plus/icons-vue'
import { ElMessage, ElMessageBox } from 'element-plus'
import Sortable from 'sortablejs'
import { getDataTypeGroups, getTypeInfo } from '@/utils/databaseTypes'

const props = defineProps({
  columns: {
    type: Array,
    default: () => []
  },
  databaseType: {
    type: String,
    default: 'mysql'
  },
  isNewTable: {
    type: Boolean,
    default: false
  }
})

const emit = defineEmits(['update'])

// 响应式数据
const localColumns = ref([])
const selectedColumns = ref([])
const searchQuery = ref('')
const showAdvancedDialog = ref(false)
const showBatchDialog = ref(false)
const currentColumn = ref(null)
const currentColumnIndex = ref(-1)
const batchAction = ref('setNotNull')
const batchCharset = ref('')
const batchCommentPrefix = ref('')
const tableMaxHeight = ref(600)

let sortableInstance = null

// 计算属性
const dataTypeGroups = computed(() => getDataTypeGroups(props.databaseType))

const filteredColumns = computed(() => {
  if (!searchQuery.value) return localColumns.value
  const query = searchQuery.value.toLowerCase()
  return localColumns.value.filter(col => 
    col.name.toLowerCase().includes(query) ||
    col.type.toLowerCase().includes(query) ||
    (col.comment && col.comment.toLowerCase().includes(query))
  )
})

// 监听器
watch(() => props.columns, (newColumns) => {
  localColumns.value = newColumns.map((col, index) => ({
    ...col,
    _id: col._id || `col_${Date.now()}_${index}`,
    semanticType: col.semanticType || 'BYTE' // 为达梦数据库添加默认字符语义
  }))
}, { immediate: true, deep: true })

// 生命周期
onMounted(() => {
  calculateTableHeight()
  window.addEventListener('resize', calculateTableHeight)
  
  nextTick(() => {
    initSortable()
  })
})

onBeforeUnmount(() => {
  window.removeEventListener('resize', calculateTableHeight)
  if (sortableInstance) {
    sortableInstance.destroy()
  }
})

// 计算表格高度
const calculateTableHeight = () => {
  tableMaxHeight.value = window.innerHeight - 300
}

// 初始化拖拽
const initSortable = () => {
  const tbody = document.querySelector('.modern-table .el-table__body tbody')
  if (!tbody) return

  sortableInstance = new Sortable(tbody, {
    handle: '.drag-handle',
    animation: 200,
    ghostClass: 'opacity-50',
    dragClass: 'shadow-lg',
    onEnd: (evt) => {
      if (evt.oldIndex === evt.newIndex) return
      
      const movedItem = localColumns.value.splice(evt.oldIndex, 1)[0]
      localColumns.value.splice(evt.newIndex, 0, movedItem)
      emitUpdate()
    }
  })
}

// 方法
const addColumn = () => {
  // 构建默认列配置
  const columnDefaults = {
    _id: `col_${Date.now()}`,
    name: `column_${localColumns.value.length + 1}`,
    notNull: false,
    primaryKey: false,
    autoIncrement: false,
    unique: false,
    comment: ''
  }
  
  // 根据数据库类型设置默认值
  if (props.databaseType === 'mysql') {
    columnDefaults.type = 'varchar'
    columnDefaults.length = 255
  } else if (props.databaseType === 'postgresql') {
    columnDefaults.type = 'character varying'
    columnDefaults.length = 255
  } else if (props.databaseType === 'sqlite') {
    columnDefaults.type = 'TEXT'
  } else if (props.databaseType === 'sqlserver') {
    columnDefaults.type = 'nvarchar'
    columnDefaults.length = 255
  } else if (props.databaseType === 'dameng') {
    columnDefaults.type = 'VARCHAR2'
    columnDefaults.length = 255
    columnDefaults.semanticType = 'BYTE' // 达梦特有的字符语义
  } else {
    columnDefaults.type = 'varchar'
    columnDefaults.length = 255
  }
  
  localColumns.value.push(columnDefaults)
  emitUpdate()
}

const removeColumn = (index) => {
  ElMessageBox.confirm(
    `确定要删除列 "${localColumns.value[index].name}" 吗？`,
    '删除确认',
    {
      confirmButtonText: '删除',
      cancelButtonText: '取消',
      type: 'warning'
    }
  ).then(() => {
    localColumns.value.splice(index, 1)
    emitUpdate()
    ElMessage.success('列已删除')
  }).catch(() => {})
}

const handleSelectionChange = (selection) => {
  selectedColumns.value = selection
}

const handleCellDblClick = (row, column, cell, event) => {
  // 双击单元格时可以快速编辑
  const input = cell.querySelector('input')
  if (input) {
    input.focus()
  }
}

const showAdvancedOptions = (index) => {
  currentColumn.value = { ...localColumns.value[index] }
  
  // 确保达梦特有的字段有默认值
  if (props.databaseType === 'dameng' && !currentColumn.value.semanticType) {
    currentColumn.value.semanticType = 'BYTE'
  }
  
  currentColumnIndex.value = index
  showAdvancedDialog.value = true
}

const saveAdvancedOptions = () => {
  if (currentColumnIndex.value >= 0) {
    localColumns.value[currentColumnIndex.value] = { ...currentColumn.value }
    emitUpdate()
  }
  showAdvancedDialog.value = false
}

const batchOperations = () => {
  if (selectedColumns.value.length === 0) {
    ElMessage.warning('请先选择要操作的列')
    return
  }
  showBatchDialog.value = true
}

const executeBatchOperation = () => {
  const selectedIds = selectedColumns.value.map(col => col._id)
  
  localColumns.value.forEach(col => {
    if (!selectedIds.includes(col._id)) return
    
    switch (batchAction.value) {
      case 'setNotNull':
        col.notNull = true
        break
      case 'removeNotNull':
        col.notNull = false
        break
      case 'setCharset':
        if (isStringType(col.type)) {
          col.charset = batchCharset.value
        }
        break
      case 'setComment':
        col.comment = batchCommentPrefix.value + (col.comment || '')
        break
    }
  })
  
  emitUpdate()
  showBatchDialog.value = false
  ElMessage.success('批量操作完成')
}

const handleColumnChange = (index) => {
  // 验证列名是否为空
  if (!localColumns.value[index].name) {
    ElMessage.warning('列名不能为空')
    localColumns.value[index].name = `column_${index + 1}`
  }
  
  // 验证列名是否重复
  const names = localColumns.value.map(col => col.name.toLowerCase())
  const duplicates = names.filter((name, i, arr) => arr.indexOf(name) !== i)
  if (duplicates.length > 0) {
    ElMessage.warning(`发现重复的列名: ${duplicates.join(', ')}`)
    // 不阻止保存，只是警告
  }
  
  // 针对达梦特有的处理
  if (props.databaseType === 'dameng') {
    const column = localColumns.value[index]
    
    // 确保字符类型的字段有语义类型
    if (isStringType(column.type) && !column.semanticType) {
      column.semanticType = 'BYTE'
    }
  }
  
  emitUpdate()
}

const handleTypeChange = (type, index) => {
  const column = localColumns.value[index]
  const typeInfo = getTypeInfo(type, props.databaseType)
  
  // 根据类型设置默认值
  if (typeInfo.defaultLength) {
    column.length = typeInfo.defaultLength
  }
  
  // 清除不适用的属性
  if (!canAutoIncrement(column)) {
    column.autoIncrement = false
  }
  
  // 达梦特有的处理
  if (props.databaseType === 'dameng') {
    // 对于字符类型，确保有语义类型设置
    if (isStringType(type) && !column.semanticType) {
      column.semanticType = 'BYTE'
    }
    
    // 对于NUMBER类型，默认精度设置
    if (type.toUpperCase() === 'NUMBER' && !column.precision) {
      column.precision = 10
      column.scale = 0
    }
  }
  
  emitUpdate()
}

const handlePrimaryKeyChange = (index) => {
  const column = localColumns.value[index]
  
  if (column.primaryKey) {
    // 设置为主键时，自动设置为非空
    column.notNull = true
    
    // 检查主键列的类型是否适合
    const typeLower = column.type.toLowerCase()
    const ideaTypes = ['int', 'bigint', 'integer', 'varchar', 'char', 'uuid']
    
    const isIdealType = ideaTypes.some(t => typeLower.includes(t))
    if (!isIdealType) {
      ElMessage({
        message: `警告：${column.type} 可能不是理想的主键类型。建议使用整数或字符串类型。`,
        type: 'warning',
        duration: 5000
      })
    }
    
    // 清除其他列的主键标记（如果只允许单主键）
    if (props.databaseType !== 'postgresql' && props.databaseType !== 'mysql') {
      localColumns.value.forEach((col, i) => {
        if (i !== index) {
          col.primaryKey = false
        }
      })
    }
  }
  
  emitUpdate()
}

const handleAutoIncrementChange = (index) => {
  const column = localColumns.value[index]
  
  if (column.autoIncrement) {
    // 自增列必须是主键
    column.primaryKey = true
    column.notNull = true
    
    // 验证列类型是否支持自增
    const typeLower = column.type.toLowerCase()
    if (!['int', 'integer', 'bigint', 'smallint', 'tinyint', 'mediumint'].includes(typeLower)) {
      ElMessage({
        message: `警告：${column.type} 类型可能不支持自增。建议使用整数类型。`,
        type: 'warning',
        duration: 5000
      })
    }
    
    // 清除其他列的自增标记
    localColumns.value.forEach((col, i) => {
      if (i !== index) {
        col.autoIncrement = false
      }
    })
  }
  
  emitUpdate()
}

const setDefaultValue = (index, value) => {
  localColumns.value[index].defaultValue = value
  emitUpdate()
}

const emitUpdate = () => {
  emit('update', localColumns.value.map(col => {
    const { _id, ...columnData } = col
    return columnData
  }))
}

// 辅助方法
const needsLength = (type) => {
  if (!type) return false
  
  const typeLower = type.toLowerCase()
  const typesWithLength = ['varchar', 'varchar2', 'char', 'binary', 'varbinary', 'bit', 'character varying', 'nvarchar']
  
  // 达梦数据库的类型处理
  if (props.databaseType === 'dameng') {
    return typesWithLength.includes(typeLower) || 
           typeLower === 'nchar' || 
           typeLower.includes('varchar')
  }
  
  return typesWithLength.includes(typeLower)
}

const needsPrecision = (type) => {
  if (!type) return false
  
  const typeLower = type.toLowerCase()
  const typesWithPrecision = ['decimal', 'numeric', 'float', 'double', 'number']
  
  return typesWithPrecision.includes(typeLower)
}

const canAutoIncrement = (column) => {
  if (!column || !column.type) return false
  
  const typeLower = column.type.toLowerCase()
  const autoIncrementTypes = ['int', 'integer', 'bigint', 'smallint', 'tinyint', 'mediumint', 'serial']
  
  // 达梦数据库支持NUMBER类型作为自增列
  if (props.databaseType === 'dameng') {
    return autoIncrementTypes.includes(typeLower) || typeLower === 'number'
  }
  
  return autoIncrementTypes.includes(typeLower)
}

const isStringType = (type) => {
  if (!type) return false
  
  const typeLower = type.toLowerCase()
  const stringTypes = ['varchar', 'varchar2', 'char', 'text', 'tinytext', 'mediumtext', 'longtext', 'character varying', 'nvarchar', 'nchar']
  
  return stringTypes.includes(typeLower) || typeLower.includes('char')
}

const getLengthPlaceholder = (type) => {
  if (!type) return '长度'
  
  if (needsPrecision(type)) return '精度'
  return '长度'
}

const getTypeIcon = (type) => {
  if (!type) return Document
  
  const typeMap = {
    'varchar': Document,
    'varchar2': Document,
    'char': Document,
    'text': Document,
    'int': Key,
    'integer': Key,
    'bigint': Key,
    'number': Key,
    'datetime': Calendar,
    'timestamp': Clock,
    'json': Link
  }
  return typeMap[type.toLowerCase()] || Document
}

const getTypeIconClass = (type) => {
  if (!type) return 'text-gray-500'
  
  const classMap = {
    'varchar': 'text-blue-500',
    'varchar2': 'text-blue-500',
    'char': 'text-blue-500',
    'text': 'text-blue-500',
    'int': 'text-green-500',
    'integer': 'text-green-500',
    'bigint': 'text-green-500',
    'number': 'text-green-500',
    'datetime': 'text-purple-500',
    'timestamp': 'text-purple-500',
    'json': 'text-orange-500'
  }
  return classMap[type.toLowerCase()] || 'text-gray-500'
}

// 处理非空约束变更
const handleNotNullChange = (index) => {
  const column = localColumns.value[index]
  
  // 当设置为非空时，显示警告
  if (column.notNull && !props.isNewTable) {
    // 检查是否已有默认值
    if (!column.defaultValue) {
      // 提示用户添加默认值
      ElMessageBox.confirm(
        `将列 "${column.name}" 设为非空可能导致修改失败，如果表中已有NULL值。建议添加默认值。`,
        '添加默认值',
        {
          confirmButtonText: '添加默认值',
          cancelButtonText: '保持现状',
          type: 'warning',
          showInput: true,
          inputPlaceholder: '请输入默认值',
          inputValue: suggestDefaultValue(column.type)
        }
      ).then(({ value }) => {
        if (value !== undefined) {
          column.defaultValue = value
        }
        handleColumnChange(index)
      }).catch(() => {
        // 用户取消，但保持非空设置
        handleColumnChange(index)
      })
    } else {
      handleColumnChange(index)
    }
  } else {
    // 未设置非空或是新表，直接更新
    handleColumnChange(index)
  }
}

// 智能推荐默认值
const suggestDefaultValue = (type) => {
  if (!type) return ''
  
  const typeLower = type.toLowerCase()
  
  // 根据类型推荐合适的默认值
  if (typeLower.includes('int') || typeLower.includes('number')) {
    return '0'
  } else if (typeLower.includes('varchar') || typeLower.includes('char') || typeLower.includes('text')) {
    return ''
  } else if (typeLower.includes('datetime') || typeLower.includes('timestamp')) {
    return 'CURRENT_TIMESTAMP'
  } else if (typeLower === 'date') {
    return 'CURRENT_DATE'
  } else if (typeLower.includes('decimal') || typeLower.includes('float') || typeLower.includes('double')) {
    return '0.00'
  } else if (typeLower.includes('bool')) {
    return 'false'
  }
  
  return ''
}
</script>

<style lang="scss" scoped>
.table-columns-panel-v2 {
  height: 100%;
  display: flex;
  flex-direction: column;
  
  .panel-header {
    flex-shrink: 0;
  }
  
  .table-container {
    flex: 1;
    overflow: hidden;
    background-color: #f5f7fa;
  }
  
  // 现代化表格样式
  .modern-table {
    width: 100%;
    
    :deep(.el-table__header) {
      th {
        background-color: #f8f9fa !important;
        color: #606266;
        font-weight: 600;
        
        .cell {
          line-height: 23px;
        }
      }
    }
    
    :deep(.el-table__body) {
      td {
        padding: 8px 0;
        
        .cell {
          display: flex;
          align-items: center;
          min-height: 32px;
        }
      }
      
      // 悬停效果
      tr:hover {
        td {
          background-color: #f5f7fa !important;
        }
      }
    }
    
    // 固定列阴影
    :deep(.el-table__fixed) {
      box-shadow: 1px 0 8px rgba(0, 0, 0, 0.08);
    }
    
    :deep(.el-table__fixed-right) {
      box-shadow: -1px 0 8px rgba(0, 0, 0, 0.08);
    }
  }
  
  // 输入框样式优化
  .column-input {
    :deep(.el-input__wrapper) {
      box-shadow: none;
      border: 1px solid transparent;
      background-color: transparent;
      
      &:hover {
        border-color: #dcdfe6;
        background-color: #fff;
      }
      
      &:focus-within {
        border-color: var(--el-color-primary);
        background-color: #fff;
      }
    }
  }
  
  // 约束复选框样式
  .constraints-checkboxes {
    display: flex;
    align-items: center;
    gap: 12px;
    flex-wrap: wrap;
    
    :deep(.el-checkbox) {
      margin-right: 0;
      
      .el-checkbox__label {
        font-size: 13px;
        color: #606266;
      }
    }
  }
  
  // 空状态样式
  .empty-state {
    background-color: white;
    border-radius: 8px;
    box-shadow: 0 2px 12px 0 rgba(0, 0, 0, 0.1);
  }
  
  // 拖拽样式
  .drag-handle {
    &:active {
      cursor: grabbing;
    }
  }
  
  // 响应式设计
  @media (max-width: 1440px) {
    .modern-table {
      :deep(.el-table__body) {
        td {
          padding: 6px 0;
        }
      }
    }
  }
}

// 暗色模式
@media (prefers-color-scheme: dark) {
  .table-columns-panel-v2 {
    .table-container {
      background-color: #1a1a1a;
    }
    
    .modern-table {
      :deep(.el-table__header) {
        th {
          background-color: #2a2a2a !important;
          color: #e4e7ed;
        }
      }
      
      :deep(.el-table__body) {
        tr:hover {
          td {
            background-color: #2a2a2a !important;
          }
        }
      }
    }
    
    .empty-state {
      background-color: #2a2a2a;
    }
  }
}
</style> 